package com.ken.consumer;

import com.ken.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by renchongyu on 2018/11/26.
 */
@Component
public class RabbitReceiver {

    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "queue-1",durable = "true"),
        exchange = @Exchange(value = "exchange-1",durable = "true",type = "topic",ignoreDeclarationExceptions = "true"),
        key = "springboot.*"
        )
    )
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws Exception{
        System.out.println("消息body："+message.getPayload());
        long deliveryTag = (long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);

        System.out.println("deliveryTag="+deliveryTag);
        //手工ack
        channel.basicAck(deliveryTag,false);
    }


    /**
     *
     =exchange-2
     =true
     =topic
     =true
     =springboot.*
     * @param order
     * @param channel
     * @throws Exception
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}",durable = "${spring.rabbitmq.listener.order.queue.durable}"),
            exchange = @Exchange(value = "${spring.rabbitmq.listener.order.exchange.name}",durable = "${spring.rabbitmq.listener.order.exchange.durable}",type = "${spring.rabbitmq.listener.order.exchange.type}",ignoreDeclarationExceptions = "${spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions}"),
            key = "${spring.rabbitmq.listener.order.key}"
    )
    )
    @RabbitHandler
    public void onOrderMessage(@Payload Order order, Channel channel, @Headers Map<String,Object> headers) throws Exception{
        System.out.println("消息order  body："+order.toString());
        long deliveryTag = (long)headers.get(AmqpHeaders.DELIVERY_TAG);

        System.out.println("deliveryTag="+deliveryTag);
        //手工ack
        channel.basicAck(deliveryTag,false);
    }

}
